package top.pengdong.pictureShare.tweet.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import top.pengdong.pictureShare.common.model.*;
import top.pengdong.pictureShare.common.utils.IPAddress;
import top.pengdong.pictureShare.common.utils.OauthUtils;
import top.pengdong.pictureShare.common.utils.Tool;
import top.pengdong.pictureShare.tweet.config.SensitiveWordConfig;
import top.pengdong.pictureShare.tweet.dao.PsCommentLikeDao;
import top.pengdong.pictureShare.tweet.dao.PsTweetDao;
import top.pengdong.pictureShare.tweet.entity.PsCommentEntity;
import top.pengdong.pictureShare.tweet.dao.PsCommentDao;
import top.pengdong.pictureShare.tweet.entity.PsCommentLikeEntity;
import top.pengdong.pictureShare.tweet.entity.PsTweetEntity;
import top.pengdong.pictureShare.tweet.entity.TUsersEntity;
import top.pengdong.pictureShare.tweet.service.PsCommentLikeService;
import top.pengdong.pictureShare.tweet.service.PsCommentService;
import top.pengdong.pictureShare.tweet.service.PsTweetService;

@Slf4j
@Service("psCommentService")
public class PsCommentServiceImpl extends ServiceImpl<PsCommentDao, PsCommentEntity> implements PsCommentService {

    @Autowired
    private PsCommentLikeDao psCommentLikeDao;

    @Autowired
    private PsTweetDao psTweetDao;

    @Autowired
    private PsCommentDao psCommentDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PsCommentEntity> page = this.page(
                new Query<PsCommentEntity>().getPage(params),
                new QueryWrapper<PsCommentEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 获取文章下的 评论
     * @param aid
     * @return
     */
    @Override
    public R get_comment_info(Long aid, Integer currPage, Integer limit, Long userId) {
        IPage<PsCommentEntity> page = this.page(
                new Page<>(currPage, limit),
                new QueryWrapper<PsCommentEntity>()
                        .eq("tweet_id", aid)
                        .eq("pid", 0)
        );
        // log.info("用户userId 查询 评论 数据" + aid + page.getRecords());
        for (PsCommentEntity psComment : page.getRecords()) {
            addCommentUserInfo(psComment, userId);
            psComment.setPsCommentEntities(new ArrayList<>());
            get_comment_child(psComment, psComment, 0, userId);

        }
        return R.ok("文章评论列表").put("result", new PageUtils(page));

    }

    /**
     * 递归查找子评论
     * @param psComment
     * @param father
     */
    public void get_comment_child(PsCommentEntity psComment, PsCommentEntity father, int num, Long me) {
        if (num == 80) return;
        List<PsCommentEntity> psCommentEntities = this.baseMapper.selectList(
                new QueryWrapper<PsCommentEntity>().eq(
                        "pid", psComment.getId()
                )
        );
        for (PsCommentEntity psComment1 : psCommentEntities) {
            addCommentUserInfo(psComment1, me);
            father.getPsCommentEntities().add(psComment1);
            get_comment_child(psComment1, father, num + 1, me);
        }
    }

    /**
     * 添加评论功能
     * @param psComment
     * @return
     */
    @Override
    public R comment_add(PsCommentEntity psComment) {
        PsTweetEntity psTweet = psTweetDao.selectById(psComment.getTweetId());
        if (psTweet == null) {
            return R.error(400 ,"参数错误");
        }
        if (psTweet.getIsComment() == 0) {
            return R.error(401, "不允许发布评论");
        }
        LoginVal loginVal = OauthUtils.getCurrentUser();

        if (loginVal == null || Long.valueOf(loginVal.getUserId()) != psComment.getUserId()
        || psComment.getTweetId() == null) {
            return R.error(ResultCode.CLIENT_AUTHENTICATION_FAILED.getCode(),
                    ResultCode.CLIENT_AUTHENTICATION_FAILED.getMsg());
        }
        // 禁言操作
        TUsersEntity userInfo = psTweetDao.getUserInfo(Long.valueOf(loginVal.getUserId()));
        if (userInfo.getStatus() == 0) {
            return R.error(ResultCode.USER_IS_BAN.getCode(), ResultCode.USER_IS_BAN.getMsg());
        }
        // 评论为空的情况
        if (psComment.getCommentContext().equals("")) {
            return R.error(ResultCode.NO_ENOUGH_COMMENT.getCode(),
                    ResultCode.NO_ENOUGH_COMMENT.getMsg());
        }
        if (psComment.getPid() == null) psComment.setPid(0L);

        // 添加ip属地
        psComment.setIpAddress(Tool.getAddress(psComment.getLocation()));
        psComment.setCommentContext(SensitiveWordConfig.sensitiveWordFiltering(psComment.getCommentContext()));
        psComment.setUserId(Long.valueOf(loginVal.getUserId()));
        psComment.setStatus(1);
        psComment.setPsCommentEntities(new ArrayList<>());
        addCommentUserInfo(psComment, Long.valueOf(loginVal.getUserId()));
        this.save(psComment);
        return R.ok("评论添加成功").put("result", psComment);
    }

    /**
     * 删除评论操作
     * @param cid
     * @return
     */
    @Override
    public R delete_comment(Long cid) {
        log.info("删除评论 id : " + cid);
        LoginVal loginVal = OauthUtils.getCurrentUser();
        PsCommentEntity psCommentEntity = this.baseMapper.selectById(cid);

        if (psCommentEntity == null) {
            return R.error(400, "参数错误");
        }
        if (loginVal == null || Long.valueOf(loginVal.getUserId()) != psCommentEntity.getUserId()) {
            return R.error(ResultCode.CLIENT_AUTHENTICATION_FAILED.getCode(),
                    ResultCode.CLIENT_AUTHENTICATION_FAILED.getMsg());
        }

        psCommentEntity.setStatus(0);
        // System.out.println(psCommentEntity);
        psCommentDao.deleteById(psCommentEntity);
        return R.ok("删除评论成功");

    }

    /**
     * 点赞评论
     * @param cid
     * @param userId
     * @return
     */
    @Override
    public R add_like_comment(Long cid, Long userId) {
        // log.info("用户userId 添加数据" + userId + " : 评论 " + cid);
        if (psCommentLikeDao.selectCount(
                new QueryWrapper<PsCommentLikeEntity>()
                        .eq("comment_id", cid)
                        .eq("user_id", Long.valueOf(userId))) > 0
                && psCommentDao.selectById(cid) == null) {
            return R.error(400, "用户已经点赞了");
        }
        PsCommentLikeEntity psCommentLikeEntity = new PsCommentLikeEntity();
        psCommentLikeEntity.setCommentId(cid);
        psCommentLikeEntity.setUserId(userId);
        psCommentLikeEntity.setStatus(1);
        psCommentLikeDao.insert(psCommentLikeEntity);
        if (psCommentLikeEntity.getId() != null && psCommentLikeEntity.getId() > 0) {
            return R.ok("评论点赞成功");
        } else {
            return R.ok("评论点赞失败");
        }
    }

    /**
     * 取消评论点赞
     * @param cid
     * @param userId
     * @return
     */
    @Override
    public R delete_like_comment(Long cid, Long userId) {
        // log.info("用户userId 查询数据" + userId + " : 评论 " + cid);
        if (psCommentLikeDao.delete(new QueryWrapper<PsCommentLikeEntity>()
                .eq("comment_id", cid)
                .eq("user_id", userId)) != 0) {
            return R.ok("取消点赞成功");
        }
        return R.error("取消点赞失败");
    }

    /**
     * 添加用户信息
     * @param psComment
     */
    private void addCommentUserInfo(PsCommentEntity psComment, Long me) {

        TUsersEntity userInfo = psTweetDao.getUserInfo(psComment.getUserId());
        if (psComment.getToUserId() == 0 || psComment.getToUserId() == null) {
            psComment.setToUserNickname(null);
        } else {
            TUsersEntity toUserInfo = psTweetDao.getUserInfo(psComment.getToUserId());
            psComment.setToUserNickname(toUserInfo.getNickname());
        }

        psComment.setUserAvatar(userInfo.getAvatar());
        psComment.setNickname(userInfo.getNickname());


        // 查看用户点赞记录

        if (psCommentLikeDao.selectCount(
                new QueryWrapper<PsCommentLikeEntity>()
                .eq("comment_id", psComment.getId())
                .eq("user_id", me)) > 0) {
            psComment.setLike(true);
        }
    }
}